import { Controller, Post, Body, BadRequestException } from '@nestjs/common';
import { CreateTokenDto } from './dto/create-token.dto';
import { UsersService } from 'src/users/users.service';
import { JwtService } from '@nestjs/jwt';
import { PasswordService } from 'src/utils/password/password.service';

@Controller('auth')
export class AuthController {
  constructor(
    private readonly usersService: UsersService,
    private readonly jwtService: JwtService,
    private readonly passwordService: PasswordService,
  ) {}

  @Post()
  async createToken(@Body() createTokenDto: CreateTokenDto) {
    // 查找用户
    const user = await this.usersService.findOne(createTokenDto.account);
    // 判断用户是否注册
    if (!user) {
      throw new BadRequestException('请先注册用户', '用户不存在');
    }
    // 验证账号密码匹配
    if (
      !(await this.passwordService.compare(
        createTokenDto.password,
        user.password,
      ))
    ) {
      throw new BadRequestException('请重新输入账号或密码', '账号或密码错误');
    }
    // 签发令牌
    return {
      token: this.jwtService.sign({ account: createTokenDto.account }),
    };
  }
}
